package com.mgzf.sdk.util;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * AES加密解密
 * @author Charlotte
 * @time 2015年6月5日
 */
public class MogoAESUtil {

	private final static String key = "8542dges";
	/**
	 * 加密
	 * @author Charlotte
	 * @time 2015年6月5日
	 * @param content
	 * @param password
	 * @return
	 */
	public static String encrypt(String content){ 
	        try {            
	                KeyGenerator kgen = KeyGenerator.getInstance("AES"); 
	                SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );  
	                secureRandom.setSeed(MogoAESUtil.key.getBytes());  
	                kgen.init(128, secureRandom); 
	                SecretKey secretKey = kgen.generateKey(); 
	                byte[] enCodeFormat = secretKey.getEncoded(); 
	                SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES"); 
	                Cipher cipher = Cipher.getInstance("AES");// 创建密码器 
	                cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化 
	                byte[] result = cipher.doFinal(content.getBytes("utf-8")); 
	                return parseByte2HexStr(result); 
	        } catch (NoSuchAlgorithmException e) { 
	                e.printStackTrace(); 
	        } catch (NoSuchPaddingException e) { 
	                e.printStackTrace(); 
	        } catch (InvalidKeyException e) { 
	                e.printStackTrace(); 
	        } catch (IllegalBlockSizeException e) { 
	                e.printStackTrace(); 
	        } catch (BadPaddingException e) { 
	                e.printStackTrace(); 
	        } catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}  
	        return null; 
	} 

	/**
	 * 解密
	 * @author Charlotte
	 * @time 2015年6月5日
	 * @param content
	 * @param password
	 * @return
	 */
	 public static String decrypt(String content) { 
		 if(content==null||content.length()==0){
			 return content;
		 }
	         try { 
	                  KeyGenerator kgen = KeyGenerator.getInstance("AES"); 
	                  SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );  
	                  secureRandom.setSeed(MogoAESUtil.key.getBytes());  
	                  kgen.init(128, secureRandom); 
//	                  kgen.init(128, new SecureRandom(password.getBytes())); 
	                  SecretKey secretKey = kgen.generateKey(); 
	                  byte[] enCodeFormat = secretKey.getEncoded(); 
	                  SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");             
	                  Cipher cipher = Cipher.getInstance("AES");// 创建密码器 
	                 cipher.init(Cipher.DECRYPT_MODE, key);// 初始化 
	                 byte[] result = cipher.doFinal(parseHexStr2Byte(content)); 
	                 return new String(result,"utf-8"); // 加密 
	         } catch (NoSuchAlgorithmException e) { 
	                 e.printStackTrace(); 
	         } catch (NoSuchPaddingException e) { 
	                 e.printStackTrace(); 
	         } catch (InvalidKeyException e) { 
	                 e.printStackTrace(); 
	         } catch (IllegalBlockSizeException e) { 
	                 e.printStackTrace(); 
	         } catch (BadPaddingException e) { 
	                 e.printStackTrace(); 
	         } catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}  
	         return null; 
	 }
	 /**
	  * 将二进制转换成16进制 
	  * @author Charlotte
	  * @time 2015年6月5日
	  * @param buf
	  * @return
	  */
	 public static String parseByte2HexStr(byte buf[]) {  
	        StringBuffer sb = new StringBuffer();  
	        for (int i = 0; i < buf.length; i++) {  
	                String hex = Integer.toHexString(buf[i] & 0xFF);  
	                if (hex.length() == 1) {  
	                        hex = '0' + hex;  
	                }  
	                sb.append(hex.toUpperCase());  
	        }  
	        return sb.toString();  
	} 
	 
	 /**
	  * 将16进制转换为二进制 
	  * @author Charlotte
	  * @time 2015年6月5日
	  * @param hexStr
	  * @return
	  */
	 public static byte[] parseHexStr2Byte(String hexStr) {  
	         if (hexStr.length() < 1)  
	                 return null;  
	         byte[] result = new byte[hexStr.length()/2];  
	         for (int i = 0;i< hexStr.length()/2; i++) {  
	                 int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);  
	                 int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);  
	                 result[i] = (byte) (high * 16 + low);  
	         }  
	         return result;  
	 }  
	 
	 public static void main(String[] args) {
		 if(args.length >=2){
			 if(args[0].equals("-d")){
				 System.out.println(decrypt(args[1]));
			 }
			 if(args[0].equals("-e")){
				 System.out.println(encrypt(args[1]));
			 }
		 }
		 System.out.println(encrypt("root"));
		 System.out.println(encrypt("eq123456!"));

	}

    /**
     * @brief    AES加密
     * @details  ES加密
     * @param    key 加密密钥
     * @param    ivParamter 偏移量
     * @param    value 需要加密的字符串
     * @author   huliangjun
     * @date     2017-07-17 14:43:54
     * @note     huliangjun@2017-07-17 14:43:59 创建
     */
    public static String encrypt(String key, String ivParamter, String value) {
        try {
            IvParameterSpec iv = new IvParameterSpec(ivParamter.getBytes("UTF-8"));
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            byte[] encrypted = cipher.doFinal(value.getBytes());
            return Base64.encodeBase64String(encrypted);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * @brief    AES解密
     * @details  AES解密
     * @param    key 加密密钥
     * @param    ivParamter 偏移量
     * @param    encrypted 需要加密的字符串
     * @author   huliangjun
     * @date     2017-07-17 14:43:54
     * @note     huliangjun@2017-07-17 14:43:59 创建
     */
    public static String decrypt(String key, String ivParamter, String encrypted) {
        try {
            IvParameterSpec iv = new IvParameterSpec(ivParamter.getBytes("UTF-8"));
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));
            return new String(original);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
}